import { readFileSync, readdirSync } from 'fs'

export const svgBuilder = (path, perfix = 'icon') => {
	if (path === '') return;

	const files = readdirSync(path, {
		withFileTypes: true
	});

	const res = [];
	for (const file of files) {
		if (file.isDirectory()) {
			//只查询一级目录文件
		} else {
			const svg = readFileSync(`${path}/${file.name}`).toString()
				.replace(/(\r)|(\n)/g, '')
				.replace(/<svg([^>+].*?)>/, ($1, $2) => {
					//$1 => <svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80">
					//$2 =>  xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80"

					let width, height;
					let attrs = $2.replace(/(width|height)="([^>+].*?)"/g, ($$1, $$2, $$3) => {
						//$$1 => width="80"
						//$$2 => width
						//$$3 => 80

						if ($$2 === 'width') width = $$3;
						if ($$2 === 'height') height = $$3;

						//删除width和height
						return '';
					});

					if (!/(viewBox="[^>+].*?")/g.test(attrs)) attrs += ` viewBox="0 0 ${width} ${height}"`;

					return `<symbol id="icon-${file.name.replace('.svg', '')}" ${attrs}>`;
				})
				.replace('</svg>', '</symbol>')

			res.push(svg);
		}
	}

	return {
		name: 'svg-transform',
		transformIndexHtml(html) {
			return html.replace(
				'<body>',
				`<body><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display:none">${res.join('')}</svg>`
			)
		}
	}
}